<?php

/**
 * 字符串转数组
 * @param unknown $info
 * @return multitype:|unknown
 */
function string2array($info) {
	if($info == '') return array();
	$info=stripcslashes($info);
	eval("\$r = $info;");
	return $r;
}

function myencode($string,$is_arr=0) {
	if($is_arr!=0){
		$string=serialize($string);
	}
	$data = base64_encode ( $string );
	$data = str_replace ( array ('+', '/', '=' ), array ('-', '_', '' ), $data );
	return $data;
}

function mydecode($string,$is_arr=0) {
	$data = str_replace ( array ('-', '_' ), array ('+', '/' ), $string );
	$mod4 = strlen ( $data ) % 4;
	if ($mod4) {
		$data .= substr ( '====', $mod4 );
	}
	$res=base64_decode ( $data );
	if($is_arr!=0){
		$res=unserialize($res);
	}
	return $res;
}

/**
 * 数组转字符串
 * @param unknown $info
 * @return string
 */
function array2string($info) {
	if($info == '') return '';
	if(!is_array($info)) $string = stripslashes($info);
	foreach($info as $key => $val) $string[$key] = stripslashes($val);
	return addslashes(var_export($string, TRUE));
}

/**
 * 返回目录路径
 * @param unknown $path
 * @return Ambigous <string, mixed>
 */
function dir_path($path) {
	$path = str_replace('\\', '/', $path);
	if(substr($path, -1) != '/') $path = $path.'/';
	return $path;
}

/**
 * 新建目录
 * @param unknown $path
 * @param number $mode
 * @return boolean
 */
function dir_create($path, $mode = 0777) {
	if(is_dir($path)) return TRUE;
	$ftp_enable = 0;
	$path = dir_path($path);
	$temp = explode('/', $path);
	$cur_dir = '';
	$max = count($temp) - 1;
	for($i=0; $i<$max; $i++) {
		$cur_dir .= $temp[$i].'/';
		if (@is_dir($cur_dir)) continue;
		@mkdir($cur_dir, 0777,true);
		@chmod($cur_dir, 0777);
	}
	return is_dir($path);
}

/**
 * 拷贝一个目录
 * @param unknown $fromdir
 * @param unknown $todir
 * @return boolean
 */
function dir_copy($fromdir, $todir) {
	$fromdir = dir_path($fromdir);
	$todir = dir_path($todir);
	if (!is_dir($fromdir)) return FALSE;
	if (!is_dir($todir)) dir_create($todir);
	$list = glob($fromdir.'*');
	if (!empty($list)) {
		foreach($list as $v) {
			$path = $todir.basename($v);
			if(is_dir($v)) {
				dir_copy($v, $path);
			} else {
				copy($v, $path);
				@chmod($path, 0777);
			}
		}
	}
	return TRUE;
}

/**
 * 显示目录内容
 * @param unknown $path
 * @param string $exts
 * @param unknown $list
 * @return unknown
 */
function dir_list($path, $exts = '', $list= array()) {
	$path = dir_path($path);
	$files = glob($path.'*');
	foreach($files as $v) {
		$fileext = fileext($v);
		if (!$exts || preg_match("/\.($exts)/i", $v)) {
			$list[] = $v;
			if (is_dir($v)) {
				$list = dir_list($v, $exts, $list);
			}
		}
	}
	return $list;
}

/**
 * 显示目录树
 * @param unknown $dir
 * @param number $parentid
 * @param unknown $dirs
 * @return multitype:
 */
function dir_tree($dir, $parentid = 0, $dirs = array()) {
	if ($parentid == 0) $id = 0;
	$list = glob($dir.'*');
	foreach($list as $v) {
		if (is_dir($v)) {
			$id++;
			$dirs[$id] = array('id'=>$id,'parentid'=>$parentid, 'name'=>basename($v), 'dir'=>$v.'/');
			$dirs = dir_tree($v.'/', $id, $dirs);
		}
	}
	return $dirs;
}

/**
 * 删除目录
 * @param unknown $dir
 * @return boolean
 */
function dir_delete($dir) {
	$dir = dir_path($dir);
	if (!is_dir($dir)) return FALSE;
	$list = glob($dir.'*');
	foreach((array)$list as $v) {
		is_dir($v) ? dir_delete($v) : @unlink($v);
	}
	return @rmdir($dir);
}

/**
 * 生成短唯一码
 * @param unknown $input
 * @return Ambigous <string>
 */
function short($input) {
	$base32 = array ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5' );
	$hex = md5 ( $input );
	//echo "md5:".$hex.'<br>';
	$hexLen = strlen ( $hex );
	$subHexLen = $hexLen / 8;
	$output = array ();

	for($i = 0; $i < $subHexLen; $i ++) {
		$subHex = substr ( $hex, $i * 8, 8 );
		//echo $i."substr: ".$subHex.'<br>';
		$int = 0x3FFFFFFF & (1 * ('0x' . $subHex));
		//echo $i."0x3FFFFFFF: ".$int.'<br>';
		$out = '';

		for($j = 0; $j < 6; $j ++) {
			$val = 0x0000001F & $int;
			//echo $i.$j."0x0000001F: ".$val.'<br>';
			$out .= $base32 [$val];

			$int = $int >> 5;
		}

		$output [] = $out;
	}
	return $output ['0'];
}


/**
 *
 * @param 手机号码 $mb
 * @param 短信内容 $ct
 * @return string
 */
function sendMobiMsg($mbnum,$mbmsgct)	////$mb：手机号码; $ct：发信内容
{
	
	// 注释此行，避免测试发送短信  
	return  linuxSendMobiMsg($mbnum,$mbmsgct);
	
	/*$sinf=array("lkw","888888");
	 $smsObject = new COM ("PostMsg30.msg");
	//global $username,$password,$smsObject,$outmsg;
	$Proc = 0;
	$first = substr($$mbnum, 0, 2);
	if ($first < "13")
		$Proc = 1;
	$ret = $smsObject->Post($sinf[0],$sinf[1],$mbnum,$mbmsgct,$Proc,"");
	return $ret;*/
}


/**
 * LINUX 系统下专用
 * @param 手机号码 $mb
 * @param 短信内容 $ct
 * @return string
 */
function linuxSendMobiMsg($mbnum,$mbmsgct)	////$mb：手机号码; $ct：发信内容
{
	$sinf=array("lkw","888888");

	if(is_array($mbnum)) {
		$mbnum = join("+", $mbnum);
	}

	//$mbmsgct = mb_convert_encoding($mbmsgct,"GBK", "UTF-8");
	$ret = file_get_contents("http://211.147.224.154:13013/cgi-bin/sendsms?username=lkw&password=888888&to=$mbnum&text=$mbmsgct&subid=");

	if($ret == "-99"){
		//余额不足
		$ret = "-99";
	}elseif($ret == "0") {
		//发送成功
		$ret = "1";
	}else {
		//发送失败
		$ret = "0";
	}
	return $ret;
}

/**
 * PHP生成永不重复的编码
 */
function guid() {
	$charid = strtoupper(md5(uniqid(mt_rand(), true)));
	$uuid =
	substr($charid, 0, 8).
	substr($charid, 8, 4).
	substr($charid,12, 4).
	substr($charid,16, 4).
	substr($charid,20,12);
	return $uuid;
}
/**
 * 对象转数组
 */
function object_array($array) {
	if(is_object($array)) {
		$array = (array)$array;
	} if(is_array($array)) {
		foreach($array as $key=>$value) {
			$array[$key] = object_array($value);
		}
	}
	return $array;
}

/**
 * 数组变成字符串
 * @param array $arr 数组
 * @param string $field 数组的合并字段
 * @param string $split 分割字符串
 *@date 2013-6-17
 *@time 下午6:31:22
 */
function arr_to_explode($arr=array(),$field='id',$split='') {
	//数组变成字符串
	if(empty($arr)||!is_array($arr)) return false;
	$str=array();
	foreach ($arr as $v){
		$str[]=$v[$field];
	}
	if($split!=''){
		$str=implode($split, $str);
	}
	return $str;
}//end arr_to_explode

/**
 *获取角色的价格
 * @date 2013-8-8
 * @time 下午4:31:30
 * @param string $role 角色字串
 * @param unknown $price 价格数组
 * @return string | int 有价格时返回角色的价格，无价格返回价格字段名
 */
function role_price($role='',$price=array()) {
//获取角色的价格
	$myprice='';
	$role=explode(',', $role);
	if(array_intersect($role,array(7))){
		$myprice='jiasi';
	}
	if(array_intersect($role,array(8))){
		$myprice='jiasan';
	}
	if(array_intersect($role,array(9))){
		$myprice='jiaer';
	}
	if(array_intersect($role,array(1,2,10,11,12,13,14,15,16,17,20))){
		$myprice='jiayi';
	}
	if($price){
		$myprice=$price[$myprice];
	}
	return $myprice;
}//end role_price
/**
*按采购数量取采购价格
*@date 2013-8-6
*@time 上午11:55:43
*/
function num2price($pgp=array(),$num=1) {
//按采购数量取采购价格
	$pprice=0;
	if($num>=$pgp['qty1']&&($num<$pgp['qty2']||$pgp['qty2']==0)){
		$pprice=$pgp['price1'];
	}
	if($num>=$pgp['qty2']&&$pgp['qty2']>0&&($num<$pgp['qty3']||$pgp['qty3']==0)){
		$pprice=$pgp['price2'];
	}
	if($num>=$pgp['qty3']&&$pgp['qty3']>0&&($num<$pgp['qty4']||$pgp['qty4']==0)){
		$pprice=$pgp['price3'];
	}
	if($num>=$pgp['qty4']&&$pgp['qty4']>0&&($num<$pgp['qty5']||$pgp['qty4']==0)){
		$pprice=$pgp['price4'];
	}
	if($num>=$pgp['qty5']&&$pgp['qty5']>0){
		$pprice=$pgp['price5'];
	}
	return $pprice;
}//end num2price

function sysmd5($str, $key = '', $type = 'sha1') {
	$key = $key ? $key : C ( 'ADMIN_ACCESS' );
	return hash ( $type, $str . $key );
}
function pwdHash($password, $type = 'md5') {
	return hash ( $type, $password );
}

/**
 *
 * @param string $string
 *        	原文或者密文
 * @param string $operation
 *        	操作(ENCODE | DECODE), 默认为 DECODE
 * @param string $key
 *        	密钥
 * @param int $expiry
 *        	密文有效期, 加密时候有效， 单位 秒，0 为永久有效
 * @return string 处理后的 原文或者 经过 base64_encode 处理后的密文
 *        
 * @example $a = authcode('abc', 'ENCODE', 'key');
 *          $b = authcode($a, 'DECODE', 'key'); // $b(abc)
 *         
 *          $a = authcode('abc', 'ENCODE', 'key', 3600);
 *          $b = authcode('abc', 'DECODE', 'key'); // 在一个小时内，$b(abc)，否则 $b 为空
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;
	// 随机密钥长度 取值 0-32;
	// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
	// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
	// 当此值为 0 时，则不产生随机密钥
	$keya = md5 ( substr ( $key, 0, 16 ) );
	$keyb = md5 ( substr ( $key, 16, 16 ) );
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : '';
	$cryptkey = $keya . md5 ( $keya . $keyc );
	$key_length = strlen ( $cryptkey );
	$string = $operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string;
	$string_length = strlen ( $string );
	$result = '';
	$box = range ( 0, 255 );
	$rndkey = array ();
	for($i = 0; $i <= 255; $i ++) {
		$rndkey [$i] = ord ( $cryptkey [$i % $key_length] );
	}
	for($j = $i = 0; $i < 256; $i ++) {
		$j = ($j + $box [$i] + $rndkey [$i]) % 256;
		$tmp = $box [$i];
		$box [$i] = $box [$j];
		$box [$j] = $tmp;
	}
	for($a = $j = $i = 0; $i < $string_length; $i ++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box [$a]) % 256;
		$tmp = $box [$a];
		$box [$a] = $box [$j];
		$box [$j] = $tmp;
		$result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) );
	}
	if ($operation == 'DECODE') {
		if ((substr ( $result, 0, 10 ) == 0 || substr ( $result, 0, 10 ) - time () > 0) && substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 )) {
			return substr ( $result, 26 );
		} else {
			return '';
		}
	} else {
		return $keyc . str_replace ( '=', '', base64_encode ( $result ) );
	}
}

/**
 * 分类的树形菜单生成函数
 * 
 * @param array $arr
 *        	需要树形化的数组
 * @param string $usls
 *        	URL的类和方法
 * @return string $str
 */
function tree($arr, $urls = 'Cat/all') {
	$str = '';
	$rel = str_replace ( '/', '_', $urls );
	$pid = isset ( $_REQUEST ['pid'] ) ? intval ( $_REQUEST ['pid'] ) : 1;
	foreach ( $arr as $key => $v ) {	
		$ckd = ($pid == $v ['id']) ? 'myselect="selected"' : '';
		if ($v ['level'] < 10) {
			$str .= "<li " . $ckd . "><a href=\"" . U ( $urls, array (
					"pid" => $v ['id'] 
			) ) . "\" target=\"navTab\" rel=\"" . $rel . '_' . $v ['id'] . "\">" . $v ['name'] . '</a>';
			if ($v ['_child']) {
				$str .= "<ul>";
				$str .= tree ( $v ['_child'] );
				$str .= "</ul>";
			}
		} else {
			$str .= "<li><a href=\"javascript:void(0);\">" . $v ['name'] . '</a>';
		}
		$str .= "</li>";
	}
	return $str;
}

function clearnl($str) {
	$str = str_replace ( "\n", "", $str );
	$str = str_replace ( "\r", "", $str );
	$str = str_replace ( "\r\n", "", $str );
	return $str;
}
function getuserid() {
	return $_SESSION ['userid'];
}

/**
 * 将日期格式转为时间戳
 * 
 * @param $time 格式化的日期如
 *        	2012-09-03
 */
function gettime($time) {
	if (stripos ( $time, ' ' ) !== FALSE) {
		$temp = explode ( ' ', $time );
		$date = $temp ['0'];
		$time = $temp ['1'];
		if (stripos ( $date, '-' ) !== FALSE) {
			$date = explode ( '-', $date );
		}
		if (stripos ( $time, ':' ) !== FALSE) {
			$time = explode ( ':', $time );
		}
		$starttime = mktime ( $time ['0'], $time ['1'], $time ['2'], $date ['1'], $date ['2'], $date ['0'] );
	} else {
		if (stripos ( $time, '-' ) !== FALSE) {
			$temp = explode ( '-', $time );
			$starttime = mktime ( 0, 0, 0, $temp ['1'], $temp ['2'], $temp ['0'] );
		}
	}
	return $starttime;
}

/**
 * 取数组内的一个元素值为数组索引
 */
function field2key($arr=array(), $field='',$levle=1) {
	$newarr = array ();
	if (is_array ( $arr )) {
		foreach ( $arr as $v ) {
			if($levle==1){
				$newarr [$v [$field]] = $v;
			}else{
				$newarr [$v [$field]][] = $v;
			}
		}
	} else {
		$newarr = $arr;
	}
	return $newarr;
}

/**
 * 二维数组返回一维或字符串
 * @param array $_arr
 * @param string $_field
 * @param string $_type 1为数组 2为字符串
 * @return multitype:array|multitype:string
 */
function arr2to1($_arr,$_field = 'id',$_type = '1'){
	if ( ! $_arr ) return array();
	$arrayids = array();
	foreach ($_arr as $k => $v){
		if(is_array($v[$_field])){
			foreach ($v[$_field] as $key => $val){
				$arrayids[] = $val[$_field];
			}
		}else{
			$arrayids[] = $v[$_field];
		}
	}
	if($_type != '1') $arrayids = implode(',',$arrayids);
	 
	return $arrayids;
}

/**
 * 将字符格式化后转为数组对应键的值
 * 
 * @param unknown_type $str        	
 * @param 对应数组 $arr        	
 * @param 对应数组值的键名 $val        	
 * @param 分割间隔符 $spl        	
 * @param 组合间隔符 $impl        	
 */
function str2array_value($str, $arr, $val, $spl = ',', $impl = '/') {
	if (stripos ( $str, $spl ) !== false) {
		$str = explode ( $spl, $str );
		$newarr = array ();
		if (count ( $str ) > 0) {
			foreach ( $str as $v ) {
				$newarr [] = $arr [$v] [$val];
			}
			$str = implode ( $impl, $newarr );
		}
	} else {
		$str = $arr [$str] [$val];
	}
	return $str;
}

/**
 * 对url或其它字符转义,适合URL传输
 * json_encode + urldecode
 * 
 * @param string/array $data        	
 * @return string
 */
function myjson($code) {
	$code = json_encode (urlencodeAry ( $code ) );
	return urldecode ( $code );
}

/**
 * 对数组进行递归的urlencode操作
 * 
 * @param string/array $data        	
 * @return string/array
 */
function urlencodeAry($data) {
	if (is_array ( $data )) {
		foreach ( $data as $key => $val ) {
			$data [$key] = urlencodeAry ( $val );
		}
		return $data;
	} else {
		return urlencode ( $data );
	}
}